package top.codedance.iotp.tools.earlyWarning;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.util.HttpRequestUtil;
import top.codedance.iotp.iot.sdk.*;
import top.codedance.iotp.iot.sdk.util.StompTool;
import top.codedance.iotp.tools.earlyWarning.plugin.MyPlayer;
import top.codedance.iotp.tools.earlyWarning.ui.AlertFrame;
import top.codedance.iotp.tools.earlyWarning.ui.LoginJFrame;
import top.codedance.iotp.tools.earlyWarning.ui.SettingsFrame;

import java.io.*;
import java.util.Random;

import top.codedance.iotp.tools.earlyWarning.util.FileTool;
import org.ini4j.Ini;
import org.ini4j.Wini;
import org.java_websocket.handshake.ServerHandshake;

import javax.swing.*;

public class EarlyWarningApplication {
    public static Wini ini = null; //ini文件读取器
    public static SettingsFrame sf;
    public static String httpApi = "http://cqly.bamtechnology.cn/anon/user/api/client/login";
    public static String websocketUrl = "ws://cqly.bamtechnology.cn/anon/websocket";
    public static String tenantId = "";
    public static AlertFrame alertFrame;
    public static LoginJFrame loginJFrame;
    public static MyPlayer myPlayer;
    private static String id = String.valueOf(new Random().nextLong());
    private static final String NAME = "earlyWarning";
    public static String wavPath;
    public static String logoPath;
    public static String warningPath;
    public static String iniPath;
    public static boolean isStopWarning = false;

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel()");
        } catch (Exception e) {
        }
        tmpInit();
        sf = new SettingsFrame();
        alertFrame = new AlertFrame();
        initConfig();
        if (websocketUrl.equals("") || httpApi.equals("")) {
            sf.setVisible(true);
        }
        while (true) {
            if (tenantId.equals("")) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
                continue;
            }
            runSocket();
            break;
        }
    }

    private static void tmpInit() {
        String tmpdir = System.getProperty("java.io.tmpdir");
        String myTmpDir = tmpdir + NAME;
        FileTool.mkdirs(myTmpDir);
        System.out.println("临时工作目录：" + tmpdir);
        iniPath = myTmpDir + File.separator + "settings.ini";
        wavPath = myTmpDir + File.separator + "warning.wav";
        FileTool.fromJarCopyFile(EarlyWarningApplication.class.getResourceAsStream("/warning.wav"), wavPath);
        logoPath = myTmpDir + File.separator + "logo.gif";
        FileTool.fromJarCopyFile(EarlyWarningApplication.class.getResourceAsStream("/logo.gif"), logoPath);
        warningPath = myTmpDir + File.separator + "warning.gif";
        FileTool.fromJarCopyFile(EarlyWarningApplication.class.getResourceAsStream("/warning.gif"), warningPath);
    }

    private static void initConfig() {
        loginJFrame = new LoginJFrame();
        File f = new File(iniPath);
        if (!f.exists()) {
            try {
                f.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            ini = new Wini(f);
            if (ini.containsKey("client")) {
                Ini.Section section = ini.get("client");
                if (section.containsKey("httpApi")) {
                    if (!section.get("httpApi").equals("")) {
                        httpApi = section.get("httpApi");
                    }
                }
                if (section.containsKey("websocketUrl")) {
                    if (!section.get("websocketUrl").equals("")) {
                        websocketUrl = section.get("websocketUrl");
                    }
                }
            }
            sf.setHttpapi(httpApi);
            sf.setWebsocketUrl(websocketUrl);
            if (ini.containsKey("auth")) {
                Ini.Section section2 = ini.get("auth");
                boolean isAutoRemember = false;
                if (section2.containsKey("isAutoRemember")) {
                    isAutoRemember = section2.get("isAutoRemember", Boolean.class);
                }
                String username = "";
                if (section2.containsKey("username")) {
                    username = section2.get("username");
                }
                String password = "";
                if (section2.containsKey("password")) {
                    password = section2.get("password");
                }
                boolean isAutoLogin = false;
                if (section2.containsKey("isAutoLogin")) {
                    isAutoLogin = section2.get("isAutoLogin", Boolean.class);
                }
                if (isAutoRemember) {
                    loginJFrame.setUsername(username);
                    loginJFrame.setPassword(password);
                    loginJFrame.setAutoRemember(isAutoRemember);
                    loginJFrame.setAutoLogin(isAutoLogin);
                }
                if (isAutoLogin) {
                    login(username, password, isAutoRemember, isAutoLogin);
                } else {
                    loginJFrame.setVisible(true);
                }
            } else {
                loginJFrame.setVisible(true);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void logout() {
        loginJFrame.setVisible(true);
    }

    public static void login(String username, String password, boolean isAutoRemember, boolean isAutoLogin) {
        JSONObject jo = new JSONObject();
        jo.put("username", username);
        jo.put("password", password);
        JSONObject post = HttpRequestUtil.post(httpApi, jo.toJSONString());
        if (post.containsKey("status") && post.getBoolean("status")) {
            if (post.containsKey("data")) {
                tenantId = post.getString("data");
                loginJFrame.setVisible(false);
                if (isAutoRemember) {
                    try {
                        saveLogin(isAutoRemember, isAutoLogin, username, password);
                    } catch (Exception e) {
                    }
                }
            } else {
                JOptionPane.showMessageDialog(loginJFrame.getRootPane(), "登陆失败");
                loginJFrame.setVisible(true);
            }
        } else {
            JOptionPane.showMessageDialog(loginJFrame.getRootPane(), "登陆失败");
            loginJFrame.setVisible(true);
        }
    }

    public static void saveLogin(boolean isAutoRemember, boolean isAutoLogin, String username, String password) throws Exception {
        ini.add("auth", "isAutoRemember", isAutoRemember);
        ini.add("auth", "isAutoLogin", isAutoLogin);
        ini.add("auth", "username", username);
        ini.add("auth", "password", password);
        ini.store();
    }

    public static void saveConfig() throws Exception {
        ini.add("client", "websocketUrl", websocketUrl);
        ini.add("client", "httpApi", httpApi);
        ini.store();
    }

    private static Client client = null;

    public static void runSocket() {
        new Thread(() -> {
            myPlayer = new MyPlayer(wavPath, false, true);
            client = new StompWsClient(websocketUrl, "/anon/msg/" + tenantId, id, new WsCallbacker() {
                public void onOpen(WsContextAdapter context, ServerHandshake shake) {
                    //do samething
                }

                public void onMessage(final WsContextAdapter context, String body) {
                    JSONObject obj = StompTool.message(body);
                    if (obj.containsKey("data")) {
                        if (!isStopWarning && obj.getBoolean("data")) {
                            myPlayer.start();
                            if (obj.containsKey("msg")) {
                                alertFrame.showFrame(obj.getString("msg"));
                            }
                        } else {
                            myPlayer.stop();
                            alertFrame.hideFrame();
                        }
                    }
                }

                public void onClose(WsContextAdapter context, int var1, String var2, boolean var3) {
                    myPlayer.stop();
                    client.destory();
                }

                public void onError(WsContextAdapter context, Exception e) {
                }
            });

            while (!client.isOver()) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }

            runSocket();
        }).start();
    }
}
